import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Inventory {
	// Map<Avtor, Spisuk ot negovite knigi>
	private Map<String, List<Book>> map = new HashMap<String, List<Book>>();

	public void add(Book book) {
		if (map.get(book.getAuthor()) != null) {
			if(!map.get(book.getAuthor()).contains(book))
				map.get(book.getAuthor()).add(book);
		} else 
		{
			List<Book> temp = new ArrayList<Book>();
			temp.add(book);
			map.put(book.getAuthor(), temp);
		}

	}

	private List<Book> searchByAuthor(BookQuery br) {
		// ArrayList arrList = (ArrayList) map.values();
		List<Book> temp = new ArrayList<Book>();
		// Collection<Book> list = map.values();
			if (map.containsKey(br.getAuthor()))
				temp.addAll(map.get(br.getAuthor()));
		return temp;
	}

	private List<Book> searchTitle(BookQuery br) 
	{
		
		Book arg;
		List<Book> temp = new ArrayList<Book>();
		Collection<List<Book>> list = map.values();
		Iterator<List<Book>> it = list.iterator();
		Iterator<Book> bIt;
		it = list.iterator();
		while (it.hasNext())
		{
			bIt = it.next().iterator();
			while (bIt.hasNext())
			{
				arg = bIt.next();
				if (arg.getTitle().equals(br.getTitle()))
					temp.add(arg);
			}
		}
		return temp;
	}

	public List<Book> decision(List<BookQuery> br)
	{
		List<Book> result = new ArrayList<Book>();
		for(BookQuery query : br)
		{
			if(query.getAuthor() != null)
				if(searchByAuthor(query) != null)
					result.addAll(searchByAuthor(query));
			else if(query.getTitle() != null)
				if(searchTitle(query) != null);
					result.addAll(searchTitle(query));
		}
		return result;
	}
}
